"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Shield, Lock, User as UserIcon, AlertCircle } from "lucide-react"
import { mockUsers } from "@/mocks/admin-data"

export default function LoginPage() {
  const router = useRouter()
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [error, setError] = useState("")
  const [isLoading, setIsLoading] = useState(false)

  const handleLogin = () => {
    if (!username || !password) {
      setError("请输入用户名和密码")
      return
    }

    setIsLoading(true)
    
    // 模拟网络延迟
    setTimeout(() => {
      const user = mockUsers.find(u => u.username === username)
      
      if (!user || password !== user.password) {
        setError("用户名或密码错误")
        setIsLoading(false)
        return
      }

      // To prevent circular reference error, create a serializable version of the user object for session storage.
      // The cycle is: user -> department -> manager (which is a user object, creating a loop).
      // We break the cycle by creating a temporary user object for the session
      // where the department object does not contain the manager property.
      const userForSession = {
        ...user,
        department: {
          ...user.department,
          manager: undefined, // Break the circular reference
        },
      };

      // Simulate session by storing user info in localStorage
      localStorage.setItem("currentUser", JSON.stringify(userForSession))
      setError("")
      router.push("/") // Redirect to dashboard after login
    }, 800)
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleLogin()
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-background to-primary/5 flex items-center justify-center p-4">
      <Card className="w-full max-w-md card-shadow border-primary/10">
        <CardHeader className="text-center space-y-4">
          <div className="mx-auto w-16 h-16 bg-primary rounded-full flex items-center justify-center animate-pulse-blue">
            <Shield className="w-8 h-8 text-white" />
          </div>
          <div>
            <CardTitle className="text-2xl font-bold text-foreground">安全联锁子系统</CardTitle>
            <CardDescription className="text-muted-foreground mt-1">Safety Interlock Subsystem</CardDescription>
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="username" className="text-foreground">用户名</Label>
            <div className="relative">
              <UserIcon className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
              <Input
                id="username"
                type="text"
                placeholder="请输入用户名"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                onKeyDown={handleKeyDown}
                className="pl-10 rounded-lg"
                autoComplete="username"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="password" className="text-foreground">密码</Label>
            <div className="relative">
              <Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
              <Input
                id="password"
                type="password"
                placeholder="请输入密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                onKeyDown={handleKeyDown}
                className="pl-10 rounded-lg"
                autoComplete="current-password"
              />
            </div>
          </div>
          
          {error && (
            <div className="flex items-center gap-2 text-destructive text-sm bg-destructive/10 p-3 rounded-lg border border-destructive/20">
              <AlertCircle className="h-4 w-4" />
              <span>{error}</span>
            </div>
          )}

          <Button 
            onClick={handleLogin} 
            className="w-full rounded-lg bg-primary hover:bg-primary/90"
            disabled={isLoading}
          >
            {isLoading ? "登录中..." : "登录系统"}
          </Button>
        </CardContent>
        <CardFooter className="text-xs text-center text-muted-foreground flex justify-center">
          <p>常州地铁五防系统 © 2024</p>
        </CardFooter>
      </Card>
    </div>
  )
} 